package com.geo.ai.model;

import lombok.Data;
import lombok.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * AI模型信息类
 * 包含模型的基本信息、状态和统计数据
 * 
 * @author GEO Team
 * @version 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AIModelInfo {
    
    // 手动添加builder方法以解决编译问题
    public static AIModelInfoBuilder builder() {
        return new AIModelInfoBuilder();
    }
    
    public static class AIModelInfoBuilder {
        private String modelId;
        private String providerName;
        private String modelName;
        private String displayName;
        private String version;
        private String description;
        private Boolean enabled;
        private ModelStatus status;
        private ModelCapability capabilities;
        private UsageStatistics usage;
        private Map<String, Object> configuration;
        private LocalDateTime createdAt;
        private LocalDateTime updatedAt;
        private LocalDateTime lastUsedAt;
        
        public AIModelInfoBuilder modelId(String modelId) {
            this.modelId = modelId;
            return this;
        }
        
        public AIModelInfoBuilder providerName(String providerName) {
            this.providerName = providerName;
            return this;
        }
        
        public AIModelInfoBuilder modelName(String modelName) {
            this.modelName = modelName;
            return this;
        }
        
        public AIModelInfoBuilder displayName(String displayName) {
            this.displayName = displayName;
            return this;
        }
        
        public AIModelInfoBuilder version(String version) {
            this.version = version;
            return this;
        }
        
        public AIModelInfoBuilder description(String description) {
            this.description = description;
            return this;
        }
        
        public AIModelInfoBuilder enabled(Boolean enabled) {
            this.enabled = enabled;
            return this;
        }
        
        public AIModelInfoBuilder status(ModelStatus status) {
            this.status = status;
            return this;
        }
        
        public AIModelInfoBuilder capabilities(ModelCapability capabilities) {
            this.capabilities = capabilities;
            return this;
        }
        
        public AIModelInfoBuilder usage(UsageStatistics usage) {
            this.usage = usage;
            return this;
        }
        
        public AIModelInfoBuilder configuration(Map<String, Object> configuration) {
            this.configuration = configuration;
            return this;
        }
        
        public AIModelInfoBuilder createdAt(LocalDateTime createdAt) {
            this.createdAt = createdAt;
            return this;
        }
        
        public AIModelInfoBuilder updatedAt(LocalDateTime updatedAt) {
            this.updatedAt = updatedAt;
            return this;
        }
        
        public AIModelInfoBuilder lastUsedAt(LocalDateTime lastUsedAt) {
            this.lastUsedAt = lastUsedAt;
            return this;
        }
        
        public AIModelInfo build() {
            AIModelInfo modelInfo = new AIModelInfo();
            modelInfo.modelId = this.modelId;
            modelInfo.providerName = this.providerName;
            modelInfo.modelName = this.modelName;
            modelInfo.displayName = this.displayName;
            modelInfo.version = this.version;
            modelInfo.description = this.description;
            modelInfo.enabled = this.enabled;
            modelInfo.status = this.status;
            modelInfo.capabilities = this.capabilities;
            modelInfo.usage = this.usage;
            modelInfo.configuration = this.configuration;
            modelInfo.createdAt = this.createdAt;
            modelInfo.updatedAt = this.updatedAt;
            modelInfo.lastUsedAt = this.lastUsedAt;
            return modelInfo;
        }
    }
    
    /**
     * 模型唯一标识
     */
    private String modelId;
    
    /**
     * 提供商名称
     */
    private String providerName;
    
    /**
     * 模型名称
     */
    private String modelName;
    
    /**
     * 模型显示名称
     */
    private String displayName;
    
    /**
     * 模型版本
     */
    private String version;
    
    /**
     * 模型描述
     */
    private String description;
    
    /**
     * 是否启用
     */
    private Boolean enabled;
    
    /**
     * 模型状态
     */
    private ModelStatus status;
    
    /**
     * 模型能力
     */
    private ModelCapability capabilities;
    
    /**
     * 使用统计
     */
    private UsageStatistics usage;
    
    /**
     * 配置信息
     */
    private Map<String, Object> configuration;
    
    /**
     * 创建时间
     */
    private LocalDateTime createdAt;
    
    /**
     * 最后更新时间
     */
    private LocalDateTime updatedAt;
    
    /**
     * 最后使用时间
     */
    private LocalDateTime lastUsedAt;
    
    /**
     * 模型状态枚举
     */
    public enum ModelStatus {
        ACTIVE("active", "活跃"),
        INACTIVE("inactive", "停用"),
        ERROR("error", "错误"),
        MAINTENANCE("maintenance", "维护中"),
        RATE_LIMITED("rate_limited", "限流中"),
        UNAVAILABLE("unavailable", "不可用");
        
        private final String code;
        private final String description;
        
        ModelStatus(String code, String description) {
            this.code = code;
            this.description = description;
        }
        
        public String getCode() {
            return code;
        }
        
        public String getDescription() {
            return description;
        }
    }
    
    /**
     * 使用统计类
     */
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class UsageStatistics {
        
        /**
         * 总调用次数
         */
        private Long totalCalls;
        
        /**
         * 成功调用次数
         */
        private Long successfulCalls;
        
        /**
         * 失败调用次数
         */
        private Long failedCalls;
        
        /**
         * 总输入Token数
         */
        private Long totalInputTokens;
        
        /**
         * 总输出Token数
         */
        private Long totalOutputTokens;
        
        /**
         * 总成本
         */
        private Double totalCost;
        
        /**
         * 平均响应时间(毫秒)
         */
        private Long averageResponseTime;
        
        /**
         * 成功率
         */
        private Double successRate;
        
        /**
         * 今日调用次数
         */
        private Long todayCalls;
        
        /**
         * 本周调用次数
         */
        private Long weekCalls;
        
        /**
         * 本月调用次数
         */
        private Long monthCalls;
        
        /**
         * 计算成功率
         */
        public double calculateSuccessRate() {
            if (totalCalls == null || totalCalls == 0) {
                return 0.0;
            }
            long successful = successfulCalls != null ? successfulCalls : 0;
            return (double) successful / totalCalls * 100;
        }
        
        /**
         * 计算总Token数
         */
        public long getTotalTokens() {
            long input = totalInputTokens != null ? totalInputTokens : 0;
            long output = totalOutputTokens != null ? totalOutputTokens : 0;
            return input + output;
        }
        
        /**
         * 计算平均每次调用成本
         */
        public double getAverageCostPerCall() {
            if (totalCalls == null || totalCalls == 0 || totalCost == null) {
                return 0.0;
            }
            return totalCost / totalCalls;
        }
        
        /**
         * 获取使用量等级
         */
        public String getUsageLevel() {
            if (totalCalls == null || totalCalls == 0) {
                return "未使用";
            }
            if (totalCalls < 100) {
                return "轻度使用";
            }
            if (totalCalls < 1000) {
                return "中度使用";
            }
            if (totalCalls < 10000) {
                return "高度使用";
            }
            return "重度使用";
        }
    }
    
    /**
     * 检查模型是否可用
     */
    public boolean isAvailable() {
        return enabled != null && enabled && 
               status == ModelStatus.ACTIVE;
    }
    
    /**
     * 检查模型是否需要维护
     */
    public boolean needsMaintenance() {
        if (usage == null) {
            return false;
        }
        
        // 成功率低于80%需要维护
        double successRate = usage.calculateSuccessRate();
        if (successRate > 0 && successRate < 80.0) {
            return true;
        }
        
        // 平均响应时间超过30秒需要维护
        if (usage.averageResponseTime != null && usage.averageResponseTime > 30000) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 获取模型健康状态
     */
    public String getHealthStatus() {
        if (!isAvailable()) {
            return "不健康";
        }
        
        if (needsMaintenance()) {
            return "需要关注";
        }
        
        if (usage != null) {
            double successRate = usage.calculateSuccessRate();
            if (successRate >= 95.0) {
                return "优秀";
            }
            if (successRate >= 90.0) {
                return "良好";
            }
            if (successRate >= 80.0) {
                return "正常";
            }
        }
        
        return "一般";
    }
    
    /**
     * 获取配置值
     */
    public Object getConfigValue(String key) {
        return configuration != null ? configuration.get(key) : null;
    }
    
    /**
     * 获取配置值(带默认值)
     */
    public Object getConfigValue(String key, Object defaultValue) {
        if (configuration == null) {
            return defaultValue;
        }
        return configuration.getOrDefault(key, defaultValue);
    }
    
    /**
     * 更新使用统计
     */
    public void updateUsageStats(boolean success, long responseTime, 
                                int inputTokens, int outputTokens, double cost) {
        if (usage == null) {
            usage = new UsageStatistics();
        }
        
        // 更新基本统计
        usage.totalCalls = (usage.totalCalls != null ? usage.totalCalls : 0) + 1;
        
        if (success) {
            usage.successfulCalls = (usage.successfulCalls != null ? usage.successfulCalls : 0) + 1;
        } else {
            usage.failedCalls = (usage.failedCalls != null ? usage.failedCalls : 0) + 1;
        }
        
        // 更新Token和成本统计
        usage.totalInputTokens = (usage.totalInputTokens != null ? usage.totalInputTokens : 0) + inputTokens;
        usage.totalOutputTokens = (usage.totalOutputTokens != null ? usage.totalOutputTokens : 0) + outputTokens;
        usage.totalCost = (usage.totalCost != null ? usage.totalCost : 0.0) + cost;
        
        // 更新平均响应时间
        if (usage.averageResponseTime == null) {
            usage.averageResponseTime = responseTime;
        } else {
            usage.averageResponseTime = (usage.averageResponseTime + responseTime) / 2;
        }
        
        // 重新计算成功率
        usage.successRate = usage.calculateSuccessRate();
        
        // 更新最后使用时间
        this.lastUsedAt = LocalDateTime.now();
    }
    
    /**
     * 创建默认模型信息
     */
    public static AIModelInfo createDefault(String providerName, String modelName) {
        return AIModelInfo.builder()
                .modelId(providerName + "_" + modelName)
                .providerName(providerName)
                .modelName(modelName)
                .displayName(modelName)
                .enabled(true)
                .status(ModelStatus.ACTIVE)
                .capabilities(ModelCapability.createBasicCapability())
                .usage(new UsageStatistics())
                .createdAt(LocalDateTime.now())
                .build();
    }
}